package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strings"

	"github.com/skip2/go-qrcode"
)

func QRcode(messages ...string) {
	message := messages[0]
	qtmsg := "B站未来有可能会倒闭但绝不会变质"
	if len(messages) > 1 {
		qtmsg = messages[1]
	}
	var (
		block0 = " "
		block1 = "▀"
		block2 = "▄"
		block3 = "█"
	)
	print("二维码内容:", message)
	qr, err := qrcode.New(message, qrcode.Medium)
	if err != nil {
		print("创建二维码失败: %v\n", err)
		return
	}
	qr.WriteFile(256, "二维码.png")
	var buf bytes.Buffer
	qrBitmap := qr.Bitmap()
	if runtime.GOOS == "windows" {
		QRcodeTxt(message, qtmsg)
		return
	}
	for j, y := range qrBitmap {
		if j%2 == 1 {
			for i, x := range y {
				if x {
					if qrBitmap[j-1][i] {
						buf.WriteString(block0)
					} else {
						buf.WriteString(block1)
					}
				} else {
					if qrBitmap[j-1][i] {
						buf.WriteString(block2)
					} else {
						buf.WriteString(block3)
					}
				}
			}
			buf.WriteString("\n")
		}
	}
	fmt.Print(buf.String())
}

func QRcodeTxt(message, qt string) {
	var FF []string
	DD := []rune(qt)
	for i := 0; i < len(DD); i++ {
		FF = append(FF, string(DD[i]))
	}
	for i, v := range FF {
		if lenStr(v) == 1 {
			FF[i] = " " + v
		}
	}
	lenff := len(FF)
	fm := 0
	qr, err := qrcode.New(message, qrcode.Medium)
	if err != nil {
		print("创建二维码失败: %v\n", err)
		return
	}
	qr.WriteFile(256, "二维码.png")
	var buf bytes.Buffer
	qrBitmap := qr.Bitmap()
	for y := range qrBitmap {
		for x := range qrBitmap[y] {
			if !qrBitmap[y][x] {
				buf.WriteString(FF[fm])
				fm++
				if fm == lenff {
					fm = 0
				}
			} else {
				buf.WriteString("  ")
			}
		}
		buf.WriteString("\n")
	}
	fmt.Print(buf.String())
}

func lenStr(str string) int {
	a1 := strings.Count(str, "") - 1
	a2 := len(str)
	return (a1 + a2) / 2
}
